package com.harmonypilot.modelconfig.web;

import com.harmonypilot.modelconfig.domain.ModelConfig;
import com.harmonypilot.modelconfig.dto.ModelConfigRequest;
import com.harmonypilot.modelconfig.dto.ModelConfigResponse;
import com.harmonypilot.modelconfig.service.ModelConfigAppService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/models")
public class ModelConfigController {
    private final ModelConfigAppService service;

    public ModelConfigController(ModelConfigAppService service) { this.service = service; }

    @GetMapping
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVELOPER')")
    public List<ModelConfigResponse> list(){
        return service.list().stream()
                .sorted((a,b) -> a.getPriority().compareTo(b.getPriority()))
                .map(this::toResponse).collect(Collectors.toList());
    }

    // 提供给插件等客户端：默认按能力优先级 高→低 排序
    // 支持 format=names 只返回 name 列表，便于直接使用
    @GetMapping("/ordered")
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVELOPER')")
    public Object ordered(@RequestParam(value = "format", required = false) String format){
        List<ModelConfigResponse> ordered = list();
        if ("names".equalsIgnoreCase(format)) {
            return ordered.stream().map(ModelConfigResponse::getName).collect(Collectors.toList());
        }
        return ordered;
    }

    @GetMapping("/{name}")
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVELOPER')")
    public ResponseEntity<ModelConfigResponse> get(@PathVariable String name){
        ModelConfig mc = service.getByName(name);
        if (mc == null) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(toResponse(mc));
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ModelConfigResponse> upsert(@Valid @RequestBody ModelConfigRequest req){
        ModelConfig saved = service.upsert(req);
        return ResponseEntity.created(URI.create("/api/models/" + saved.getName())).body(toResponse(saved));
    }

    @DeleteMapping("/{name}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Void> delete(@PathVariable String name){
        service.deleteByName(name);
        return ResponseEntity.noContent().build();
    }

    private ModelConfigResponse toResponse(ModelConfig mc){
        return new ModelConfigResponse(mc.getName(), mc.getModel(), mc.getUrl(), mc.getDescription(), mc.getPriority().name());
    }
}
